﻿using pomeloUnityClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleJson;
using com.mogu.util;

namespace com.liyu.pluginframe.util
{
    public class GameService
    {
        private static GameService gameService = null;

        private String url;
        private long point;
        private IGameDtSync iGameDtSync;
        private IGameSync iGameSync;

        private String username, appcode, appcode_dt_id, roomid;

        private static List<string> shunxulist = new List<string>();
        private static Dictionary<string, UserInfo> usermap = new Dictionary<string, UserInfo>();

        private static PomeloClient pomeloClient;

        /**
         * 获取实例，单例模式
         * by:王健 at:2015-08-09
         * @return
         */
        public static GameService getInstance()
        {
            if (gameService == null)
            {

                gameService = new GameService();
            }

            return gameService;

        }


        /**
         * 大厅内被动接口绑定
         * by:王健 at:2015-08-09
         * @param iGameDtSync
         */
        public void setiGameDtSync(IGameDtSync iGameDtSync)
        {
            this.iGameDtSync = iGameDtSync;
        }

        public void removeiGameDtSync()
        {
            this.iGameDtSync = null;
        }

        private bool is_Dt_sync()
        {
            if (iGameDtSync == null)
            {
                return false;

            }
            else
            {
                return true;
            }
        }

        /**
         * 大厅内被动接口绑定
         * by:王健 at:2015-08-09
         * @param iGameSync
         */
        public void setiGameSync(IGameSync iGameSync)
        {
            this.iGameSync = iGameSync;
        }


        public void removeiGameSync()
        {
            this.iGameSync = null;
        }

        private bool is_Room_sync()
        {
            if (iGameSync == null)
            {
                return false;

            }
            else
            {
                return true;
            }
        }

        /**
         * 结果初步处理，错误和result 返回
         * by:王健 at:2015-08-09
         * @param jsonObject
         * @return
         */
        private Object doResult(JsonObject jsonObject)
        {
            bool r = (bool)jsonObject.getValue("success");
            if (!r)
            {
                if (iGameDtSync != null)
                {
                    iGameDtSync.syncError((string)jsonObject.getValue("message"), (long)jsonObject.getValue("status_code",500L));
                }
                if (iGameSync != null)
                {
                    iGameSync.syncError((string)jsonObject.getValue("message"), (long)jsonObject.getValue("status_code",500L));
                }

                return null;
            }
            return jsonObject.getValue("result");
        }

        /**
         * 进入大厅接口
         * by:王健 at:2015-08-09
         * 增加token 参数，进行md5 加密判断
         * by:王健 at:2015-08-09
         * @param host
         * @param hostpoint
         * @param token
         * @param param
         */
        public void init_dt_PomeloClient(String host, int hostpoint, String token, JsonObject param)
        {
            // pomelo demo
            PomeloClient p = new PomeloClient(host + ":" + hostpoint.ToString());
            p.init();
            String[] keys = { "appcode", "appcode_dt_id", "username" };
            Tools.sign(param, token, keys);
            p.request("gate.gateHandler.queryEntry", param, (msg) =>
            {
                var a = msg.getValue("host");

                try
                {
                    if ((long)msg.getValue("code") == 200)
                    {
                        if (pomeloClient != null && msg.getValue("host").ToString() == url && (long)msg.getValue("port") == point)
                        {
                            return;
                        }
                        pomeloClient = new PomeloClient(msg.getValue("host").ToString() + ":" + msg.getValue("port").ToString());
                        pomeloClient.init();
                        url = msg.getValue("host").ToString();
                        point = (long)msg.getValue("port");

                        Tools.sign(param, token, keys);
                        /**
                         * 进入大厅
                         * by:王健 at:2015-08-09
                         * 进入大厅，获取房间列表
                         * by:王健 at:2015-08-09
                         */
                        pomeloClient.request("connector.gameHandler.add_game_dt", param, (message) =>
                        {
                            if (!is_Dt_sync())
                            {
                                return;
                            }
                            JsonArray result = (JsonArray)doResult(message);
                            if (result != null)
                            {
                                username = (string)param.getValue("username");
                                appcode = (string)param.getValue("appcode");
                                appcode_dt_id = (string)param.getValue("appcode_dt_id");
                                iGameDtSync.syncJoinDtGame(username, appcode, appcode_dt_id, url, point);
                                iGameDtSync.syncRoomList(result);
                            }

                        });

                        /**
                         * 掉线
                         * by:王健 at:2015-08-09
                         */
                        pomeloClient.On("disconnect", (event_msg) =>
                        {
                            if (!is_Dt_sync())
                            {
                                return;
                            }
                            iGameDtSync.syncQuiteDtGame(username, appcode, appcode_dt_id);

                        });

                        /**
                         * 房间用户发生变动的接口
                         * by:王健 at:2015-08-09
                         * 人员变动包括，人离开大厅
                         * by:王健 at:2015-08-09
                         */
                        pomeloClient.On("memberChanged", (event_msg) =>
                        {
                            if (!is_Dt_sync())
                            {
                                return;
                            }
                            JsonObject result = (JsonObject)doResult(event_msg);
                            if (result != null)
                            {

                                String roomid = (string)result.getValue("roomid");
                                String username = (string)result.getValue("user");
                                JsonObject userinfo = (JsonObject)result.getValue("userinfo");
                                String changed = (string)result.getValue("changed");
                                if ("exit" == changed)
                                {
                                    pomeloClient.disconnect();
                                }
                                else if ("in" == changed)
                                {
                                    iGameDtSync.syncUserJoinRoom(username, roomid, userinfo);
                                }
                                else
                                {
                                    iGameDtSync.syncUserQuiteRoom(username, roomid);
                                }
                            }

                        });

                        /**
                         * 房间状态变化：普通、在玩、满员
                         * by:王健 at:2015-08-09
                         */
                        pomeloClient.On("roomStatusChanged", (event_msg) =>
                        {
                            if (!is_Dt_sync())
                            {
                                return;
                            }
                            JsonObject result = (JsonObject)doResult(event_msg);
                            if (result != null)
                            {

                                String roomid = (string)result.getValue("roomid");
                                String status = (string)result.getValue("status");
                                iGameDtSync.syncChangeRoomStatus(roomid, status);
                            }

                        });


                    }
                }
                catch
                {

                }


            });
        }

        /**
         * 发出获取大厅内所有房间的接口， route不正确，待改动
         * by:王健 at:2015-08-09
         * @param param
         */
        public void query_room_dt_by_appcode(JsonObject param)
        {
            pomeloClient.request("connector.gameHandler.query_dt_rooms_by_appcode", param, (message) =>
            {
                if (!is_Dt_sync())
                {
                    return;
                }
                JsonArray result = (JsonArray)doResult(message);

                if (result != null)
                {
                    iGameDtSync.syncRoomList(result);
                }


            });
        }

        /**
         * 获取房间内用户，根据id， route不正确，待改动
         * by:王健 at:2015-08-09
         * @param param
         */
        public void query_room_members_info_by_roomid(JsonObject param)
        {
            pomeloClient.request("connector.gameHandler.query_room_members_info_by_roomid", param, (message) =>
            {
                if (!is_Dt_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);
                if (result != null)
                {

                    JsonArray user_arr = (JsonArray)result.getValue("users");
                    JsonObject room_info_map = (JsonObject)result.getValue("room_info_map");
                    IEnumerator<string> keys = room_info_map.Keys.GetEnumerator();

                    while (keys.MoveNext())
                    {
                        roomid = keys.Current;
                        JsonArray users = (JsonArray)room_info_map[roomid];
                        JsonArray members = new JsonArray();

                        if (user_arr != null)
                        {
                            for (int k = 0; k < users.Count; k++)
                            {
                                for (int m = 0; m < user_arr.Count; m++)
                                {

                                    if (users[k] == ((JsonObject)user_arr[m]).getValue("username"))
                                    {
                                        members.Add(user_arr[m]);
                                    }

                                }
                            }
                        }

                        iGameDtSync.syncRoomInfoById(roomid, members);
                    }


                }


            });
        }

        /**
         *  退出大厅
         * by:王健 at:2015-08-09
         */
        public void quite_dt()
        {
            if (pomeloClient == null)
            {
                return;
            }
            pomeloClient.disconnect();
            pomeloClient = null;
        }

        public List<String> get_users()
        {

            return shunxulist;
        }

        public UserInfo getUserInfo(String username)
        {
            try
            {
                return usermap[username];
            }
            catch
            {
                return null;
            }

        }

        public void clear_users()
        {
            shunxulist.Clear();
            usermap.Clear();
        }

        public void add_user(String uname)
        {
            shunxulist.Add(uname);
        }


        /**
         * 进入大厅接口
         * by:王健 at:2015-08-09
         * 增加token 参数，进行md5 加密判断
         * by:王健 at:2015-08-09
         * @param host
         * @param hostpoint
         * @param token
         * @param param
         */
        public void init_room_PomeloClient(String host, int hostpoint, String token, JsonObject param)
        {
            // pomelo demo
            pomeloClient = new PomeloClient(host + ":" + hostpoint.ToString());
            pomeloClient.init();
            String[] keys = { "appcode", "appcode_dt_id", "username" };

            Tools.sign(param, token, keys);
            /**
             * 进入大厅
             * by:王健 at:2015-08-09
             * 进入大厅，获取房间列表
             * by:王健 at:2015-08-09
             */
            pomeloClient.request("connector.gameHandler.add_game_room", param, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);
                if (result != null)
                {
                    username = (string)param.getValue("username");
                    appcode = (string)param.getValue("appcode");
                    appcode_dt_id = (string)param.getValue("appcode_dt_id");
                    roomid = (string)param.getValue("roomid");
                    shunxulist.Clear();
                    usermap.Clear();
                    UserInfo userInfo = null;
                    JsonObject user = null;
                    JsonArray user_arr = (JsonArray)result.getValue("users");
                    for (int i = 0; i < user_arr.Count; i++)
                    {

                        user = (JsonObject)user_arr[i];
                        userInfo = new UserInfo();
                        userInfo.Username = (string)user.getValue("username");
                        userInfo.Nickname = (string)user.getValue("nickname");
                        userInfo.Head = (long)user.getValue("head");
                        userInfo.Point = (long)user.getValue("point");
                        userInfo.Rank = user.getValue("rank","").ToString();
                        usermap[userInfo.Username] = userInfo;
                        shunxulist.Add(userInfo.Username);


                    }
                    iGameSync.syncRoomMembers(shunxulist, usermap);
                    iGameSync.syncInRoom();

                }


            });

            /**
             * 掉线
             * by:王健 at:2015-08-09
             */
            pomeloClient.On("disconnect", (event_data) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                iGameSync.syncQuiteRoom();

            });

            /**
             * 房间用户发生变动的接口
             * by:王健 at:2015-08-09
             * 人员变动包括，人离开大厅
             * by:王健 at:2015-08-09
             */
            pomeloClient.On("roomAddUser", (event_data) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(event_data);
                if (result != null)
                {

                    String roomid = (string)result.getValue("roomid");
                    String username = (string)result.getValue("user");
                    JsonObject user = (JsonObject)result.getValue("userinfo");
                    UserInfo userInfo = new UserInfo();
                    userInfo.Username = (string)user.getValue("username");
                    userInfo.Nickname = (string)user.getValue("nickname");
                    userInfo.Head = (long)user.getValue("head");
                    userInfo.Point = (long)user.getValue("point");
                    userInfo.Rank = (string)user.getValue("rank");

                    usermap[userInfo.Username] = userInfo;
                    shunxulist.Add(userInfo.Username);

                    iGameSync.syncMemberChange(username, true, user);
                }

            });

            /**
             * 房间用户发生变动的接口
             * by:王健 at:2015-08-09
             * 人员变动包括，人离开大厅
             * by:王健 at:2015-08-09
             */
            pomeloClient.On("onLeave", (event_data) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(event_data);
                if (result != null)
                {

                    String roomid = (string)result.getValue("roomid");
                    String username = (string)result.getValue("user");
                    usermap.Remove(username);
                    shunxulist.Remove(username);
                    iGameSync.syncMemberChange(username, false, null);
                }

            });

            pomeloClient.On("onChat", (event_data) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(event_data);
                if (result != null)
                {

                    String from = (string)result.getValue("from");
                    String to = (string)result.getValue("to");
                    String msg = (string)result.getValue("msg");
                    if (to == null)
                    {
                        iGameSync.syncChat(from, msg);
                    }
                    else
                    {
                        iGameSync.syncChat(from, to, msg);
                    }
                }

            });

            pomeloClient.On("onEndPoint", (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    JsonObject endpoints = (JsonObject)result.getValue("endpoints");


                    IEnumerator<string> iterator = endpoints.Keys.GetEnumerator();
                    String u = null;
                    while (iterator.MoveNext())
                    {
                        u = iterator.Current;
                        iGameSync.syncEndGamePoints(u, (string)endpoints[u]);
                    }

                }


            });

            pomeloClient.On("quickGame", (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                iGameSync.syncQuiteRoom();


            });

            pomeloClient.On(MainDataTool.START_GAME, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    iGameSync.syncStartGame();
                }


            });
            pomeloClient.On(MainDataTool.END_GAME, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    String from = (string)result.getValue("from");
                    if (from == null)
                    {
                        iGameSync.syncEndGame();
                    }
                    else
                    {
                        iGameSync.syncEndGame(from);
                    }

                }


            });
            pomeloClient.On(MainDataTool.UPLOAD_GAME_POINT, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    String from = (string)result.getValue("from");
                    String point = (string)result.getValue("point");
                    iGameSync.syncGamePoints(from, point);
                }


            });
            pomeloClient.On(MainDataTool.UPLOAD_END_GAME_POINT, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    String from = (string)result.getValue("from");
                    String point = (string)result.getValue("point");
                    iGameSync.syncEndGamePoints(from, point);
                }

            });
            pomeloClient.On(MainDataTool.PUSH_GAME_DATA, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    String from = (string)result.getValue("from");
                    JsonArray users = (JsonArray)result.getValue("users");
                    if (users != null && users.Count > 0)
                    {
                        String[] us = new String[users.Count];
                        iGameSync.syncGameData(from, us, result);
                    }
                    else
                    {
                        iGameSync.syncGameData(from, result);
                    }

                }


            });
            pomeloClient.On(MainDataTool.PUSH_PROPERTY_DATA, (dataEvent) =>
            {

                if (!is_Room_sync())
                {
                    return;
                }

                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {
                    String from = (string)result.getValue("from");
                    String property_flag = (string)result.getValue("property_flag");
                    JsonArray users = (JsonArray)result.getValue("users");
                    if (users != null && users.Count > 0)
                    {
                        String[] us = new String[users.Count];
                        iGameSync.syncGamePropertyInfo(from, us, property_flag);
                    }
                    else
                    {
                        iGameSync.syncGamePropertyInfo(from, property_flag);
                    }

                }


            });

            pomeloClient.On(MainDataTool.SEND_CHAT, (dataEvent) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(dataEvent);
                if (result != null)
                {

                    String from = (string)result.getValue("from");
                    String to = (string)result.getValue("to");
                    String msg = (string)result.getValue("msg");
                    if (to == null)
                    {
                        iGameSync.syncChat(from, msg);
                    }
                    else
                    {
                        iGameSync.syncChat(from, to, msg);
                    }
                }
            });
        }

        public void quite_room()
        {
            JsonObject c = new JsonObject();

            c["appcode"] = appcode;
            c["roomid"] = roomid;
            c["username"] = username;
            c["to_username"] = username;


            pomeloClient.notify("connector.gameHandler.quit_game_room", c);
        }

        public void quite_room(String user)
        {
            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            c["username"] = username;
            c["to_username"] = username;

            pomeloClient.notify("connector.gameHandler.quit_game_room", c);
        }

        public void change_room_status(String appcode, String roomid, String status)
        {
            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            c["status"] = status;


            pomeloClient.notify("connector.gameHandler.change_room_status", c);
        }

        public void syncGameRoom(String appcode, String username, String roomid, String route, String json)
        {

            JsonObject c = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(json);
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            c["route"] = route;
            c["username"] = username;
            c["from"] = username;
            pomeloClient.notify("connector.gameHandler.send_game_info_in_room", c);

        }

        public void upload_point(String appcode, String roomid, String point)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;

            c["from"] = username;
            c["point"] = point;


            pomeloClient.notify("connector.gameHandler.upload_point", c);

        }

        public void upload_end_point(String appcode, String roomid, String point)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            c["from"] = username;
            c["point"] = point;
            pomeloClient.notify("connector.gameHandler.upload_end_point", c);

        }

        public void game_round_start_by_room(String appcode, String roomid)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            pomeloClient.notify("connector.gameHandler.game_round_start_by_room", c);
            change_room_status(appcode, roomid, "playing");

        }

        public void game_round_end_by_room(String appcode, String roomid)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            pomeloClient.notify("connector.gameHandler.game_round_end_by_room", c);

        }

        public void get_game_info_by_appcode_username(String appcode)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            pomeloClient.request("connector.gameHandler.get_game_info_by_appcode_username", c, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);
                if (result != null)
                {
                    iGameSync.syncGameInfo(result);
                }


            });

        }

        public void save_game_info_by_appcode_username(String appcode, String info)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["info"] = info;
            pomeloClient.request("connector.gameHandler.save_game_info_by_appcode_username", c, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);
                if (result != null)
                {
                    iGameSync.syncGameInfo(result);
                }


            });

        }

        public void used_prop_by_appcode_username(String appcode, String prop_flag, int count)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["prop_flag"] = prop_flag;
            c["count"] = count;
            pomeloClient.request("connector.gameHandler.used_prop_by_appcode_username", c, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);
                if (result != null)
                {
                    //                        iGameSync.syncG
                }

            });

        }

        public void get_user_prop_by_appcode_username(String appcode)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            pomeloClient.request("connector.gameHandler.get_user_prop_by_appcode_username", c, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);


            });

        }

        public void add_prop_by_appcode_username(String appcode, String prop_flag, int count)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["prop_flag"] = prop_flag;
            c["count"] = count;
            pomeloClient.request("connector.gameHandler.add_prop_by_appcode_username", c, (message) =>
            {
                if (!is_Room_sync())
                {
                    return;
                }
                JsonObject result = (JsonObject)doResult(message);


            });

        }


        public void clean_point(String appcode, String roomid)
        {

            JsonObject c = new JsonObject();
            c["appcode"] = appcode;
            c["roomid"] = roomid;
            pomeloClient.notify("connector.gameHandler.clean_point", c);

        }
    }
}
